import React from 'react'
import { connect } from 'dva'
import {Form, Modal, Button, Icon, Dropdown, Menu, Row, Input, Table, Col, Radio, Select, Popconfirm} from 'antd'
import ListPage from 'widget/PageTmpl/ListPage'
import Keypress  from 'widget/Keypress'
import UserPop from 'widget/UserPop/UserPop'
import FlagBtn from 'widget/FlagBtn/FlagView'
import { mapStateToProps } from 'utils/view_utils'
import { Link, hashHistory } from 'dva/router'
import config from '../../../../config/config'
import styles from './userListStyle.less'
import {cloneDeep} from 'lodash'

const FormItem = Form.Item;
const Option = Select.Option;


const formItemLayout1 = {
	labelCol: { span: 9 }, wrapperCol: { span: 15 }
};
const routeView = ({ dispatch, model, form }) => {

	const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
	const { modelObj, namespace } = model
	//console.log("userListModel", modelObj)
	let { showAddVisible, dataSource, detailData, allRoleList, actionType, modalPageData,roleList } = modelObj
	const menu = (
		<Menu onClick={(e) => { againConfirmation(e.key) }}>
			<Menu.Item key="delete">批量删除</Menu.Item>
			<Menu.Item key="forbid">批量禁用</Menu.Item>
			<Menu.Item key="open">批量启用</Menu.Item>
		</Menu>
	)

	//todo:后台暂时未定，需要修改表头字段
	//弹框列表
	const columns = [
		{
			title: '', dataIndex: "radio", key: 'radio', width: 60,
			render: (text, record, index) => {
				return (<div>
					<Radio checked={record.checked} onChange={(e) => {
						let dataIndex = (modalPageData.pageNo - 1) * modalPageData.pageSize + index;
						dataSource.map((x, i) => {
              x.checked=i == dataIndex
						})
						dispatch({
							type: `${namespace}/updateStore`,
							payload: dataSource
						})
					}
					} > </Radio>
				</div>)
			}
		},
		{
			title: '用户账号', dataIndex: 'uid', key: 'uid', width: 100,
		},
		{
			title: '姓名', dataIndex: 'name', key: 'name', width: 100,
		},
		{
			title: '所属部门', dataIndex: 'department', key: 'department', width: 100,
		},
		{
			title: '岗位', dataIndex: 'position', key: 'position', width: 100,
		},
		{
			title: '性别', dataIndex: 'sex', key: 'sex', width: 60,
			render: (text, record, index) => {
				return {1:'男',0:'女'}[record.sex]||''
			}
		},
		{ title: '手机号', dataIndex: 'mobile', key: 'mobile', width: 100, },
		// {
		// 	title: '身份证号码', dataIndex: 'idCardNo', key: 'idCardNo', width: 130,
		// },
		{
			title: '角色', dataIndex: 'role', key: 'role', width: 130,
			render: (text, record, index) => {
				let arr = []
				let displayRoles = cloneDeep(allRoleList);
				console.log(displayRoles)
				let existRoleIds = displayRoles.map(d => d.permissionRoleId)
				if (actionType == 'edit') {
					if (record.roleList && record.roleList.length > 0) {
						arr = record.roleList.map((x) => {
							if(!existRoleIds.includes(x.permissionRoleId)){
								x.disabled = true;
								displayRoles.push(x);
							}
							return x.permissionRoleId
						})
					}
				} else {
					if (record.roleList && record.roleList.length > 0) {
						arr = record.roleList.map((x) => {
							return x.id
						})
					}
				}
				return <div>
					<Select
						disabled={true}
						mode="multiple"
						style={{ width: 150 }}
						placeholder="请选择角色"
						defaultValue={arr}
						onChange={(v) => {
							handleChange(v, index)
						}}
					>
						{displayRoles && displayRoles.map((item, index) => {
							return <Option key={index} value={item.permissionRoleId} disabled={item.disabled}>{item.name}</Option>
						})}
					</Select>
				</div>
			}
		},
	]
	
	//选中的角色
	function handleChange(values, index) {
		let arr = []
		allRoleList.map((x, i) => {
			values.map((item) => {
				if (item == x.permissionRoleId) {
					arr.push(x)
				}
			})
		})
		dataSource[index].roleList = arr;
		let ids = [];
		for (let item of arr) {
			ids.push(item.permissionRoleId);
		}
		dataSource[index].permissionRoleIdList = ids;
		dispatch({
			type: `${namespace}/updateStore`,
			payload: { dataSource }
		});
	}
	//TODO: 选中后调后台接口
	function onSubmit(obj={}) {

		let selectObj = {}
		dataSource.map((x) => {
			if (x.checked) {
				selectObj = x
			}
		})
		delete selectObj.key;
		delete selectObj.checked;
		delete selectObj.roleList;
		if (selectObj.sex == null) {
			selectObj.sex = 1;
		}
		if (actionType != 'edit') {
			dispatch({
				type: `${namespace}/createCustomer`,
				payload: {
					...selectObj, cb: () => { fresh() }
				}
			});
		} else {
			delete selectObj.authenticationId;
			delete selectObj.sex;
			selectObj.permissionRoleIds = selectObj.permissionRoleIdList;
			delete selectObj.permissionRoleIdList;
			dispatch({
				type: `${namespace}/update`,
				payload: {
					...selectObj, cb: () => {
						fresh()
					}
				}
			});
		}
	}

	// 再次确认提示框
	function againConfirmation(actionType, actionId, modalTheme = 'confirm') {
		// 设置传入的参数
		const params = { accountIdList: modelObj.biz.selectedRows.map(item => item.accountId) };

		// 当为批量操作状态时，需要额外传入参数 -- 1：批量启用；2：批量禁用
		if (['forbid', 'open'].includes(actionType)) {
			params.state = actionType === 'forbid' ? 2 : 1;
		}

		// 根据当前弹出框的操作类型，设置调用的方法
		const funName = ['singleDelete', 'delete'].includes(actionType) ? 'batchDelete' : 'batchUpdate';

		// 设置提示信息，删除时的提示信息由接口返回
		const tips = actionType === 'delete' ? '删除' : actionType === 'forbid' ? `禁用` : `启用`;

		Modal[modalTheme]({
			title: '友情提示',
			content: `确定要${tips}选中的用户吗？`,
			maskClosable: true,
			okText: '确定', cancelText: '取消',
			onOk: () => {
				dispatch({ type: `${namespace}/${funName}`, payload: { params, cb: () => modelObj.biz.refreshListDatas(true) } });
			}
		})
	}
	// 刷新列表数据
	function fresh() {
		modelObj.biz.refreshListDatas(true)
	}

	function changeStatus(item) {
		let status = 1;
		if (item.state == 1) { status = 2 }
		dispatch({
			type: `${namespace}/changeStatus`,
			payload: {
				params: { accountId: item.accountId, state: status },
				cb: () => { fresh() }
			}
		})
	}

	//todo:需要修改表头字段
	function renderSearchFields() {
		let arr = [
			{
				en_name: "uid",
				zh_name: "用户账号",
				elem_type: "Input",
				elem_valid_type: "string"
			},
			{
				en_name: "name",
				zh_name: "姓名",
				elem_type: "Input",
				elem_valid_type: "string"
			},
			{
				en_name: "mobile",
				zh_name: "手机号",
				elem_type: "Input",
				elem_valid_type: "string"
			},
			{
				en_name: "permissionRoleId",
				zh_name: "角色",
				elem_type: "Select",
				elem_valid_type: "string",
				cmpt_items: roleList,
				
			},
			{
				en_name: "state",
				zh_name: "状态",
				elem_type: "Select",
				elem_valid_type: "string",
				cmpt_items: [
					{ "label": "启用", "value": "1" },
					{ "label": "禁用", "value": "2" }
				],
			}
		];
		return arr;
	}
	//todo:需要修改表头字段
	function renderTableFields() {
		let arr = [
			{
				en_name: "username",
				zh_name: "用户账号",
				width:100
			},
			{
				en_name: "name",
				zh_name: "姓名",
				width:80
			},
			{
				en_name: "department",
				zh_name: "所属部门",
				width:560
			},
			{
				en_name: "position",
				zh_name: "岗位",
				width:130
			},
			{
				en_name: "mobile",
				zh_name: "手机号",
				width:130
			},
			{
				en_name: "roleList",
				zh_name: "角色",
				width: 150,
				render: (text, record) => {
					let arr = [];
					record.roleList && record.roleList.forEach((e) => {
						let name = e.name;
                        arr.push(name);
                        //console.log(record.roleList)
					});
					return <div title={arr.join(',')}> {arr.join(',')}</div>
				}
			},
			
			 {
				en_name: "status",
				zh_name: "状态",
				widht:70,
				render: (text, record) => {
					return <div>{record.state == 1 ? '启用' : '禁用'}</div>
				}
			},
			{
				en_name: "updateTime",
				zh_name: "修改时间",
				width:180,
			},];

		return arr
	}

	let pageProps = {
		ui: {
			api_url: "admin/permissionAdmin/listQuery",
			method: "POST",
			app: "",
			params: "",
			mockData: null,
			search_bar: {
				fields: renderSearchFields()
			},
			action_bar: [
				{
					func_name: "onBatDel",
					label: "批量删除",
					rowSelection: (selectedRowKeys, selectedRows) => { },
					render: () => {
						let isDisabled = true;
						if (modelObj.biz && modelObj.biz.selectedRows && modelObj.biz.selectedRows.length != 0) {
							isDisabled = false;
						}
						return (
							<Dropdown overlay={menu} disabled={isDisabled} >
								<Button style={{marginRight:'15px'}}>
									批量操作 <Icon type="down" />
								</Button>
							</Dropdown>
						)
					}
				},
				{
					func_name: "onAdd",
					label: "新增",
					type: "primary",
					btnId:'100101',
					icon: "plus",
					onClick: (e) => {
						goUserAdd()
					},
				}
			],
			// 数据表格
			table: {
				fields: renderTableFields(),
				scroll: { x: 1600 },
				action_props: {
					width: 160,
					fixed: 'right',
				},
				actions: [
				// 	{
				// 	func_name: "onEdit",
				// 	label: "",
				// 	render: (item) => {
				// 		return <FlagBtn
                //                 node={<a href='javascript:;' onClick={e => {
                //                     item.checked = true;
                //                     let arr = [item];
                //                     dispatch({
                //                         type: `${namespace}/updateStore`,
                //                         payload: { showAddVisible: true, actionType: "edit", dataSource: arr }
                //                     })
                //                 }}>编辑</a>}
                //                 btnId={'801-02'}>
                //             	</FlagBtn>

				// 	}
				// },
				{
					render: (item) => {
						//console.log(item,item.accountId)
						return <FlagBtn
                                node={<a  onClick={() => timeSkip(item.accountId)}>编辑</a>}
                                btnId={'100102'}>
                            	</FlagBtn>

					}
				},
				{
					
					render: (item) => {

							if(item.state == 1){
                               return <FlagBtn
                                       node={<a  onClick={e => { changeStatus(item) }}>禁用</a>}
                                       btnId={'100103'}>
                                    </FlagBtn>

							}else {
                                return <a  onClick={e => { changeStatus(item) }}>启用</a>
							}

					}
				},
				{
					func_name: "onDelete",
					label: "删除",
					api_url: `admin/permissionAdmin/delete`,
                    btnId:'100104',
					params: 'accountId=',
					method: 'POST'
				}
				],
			}
		}
	}

	if (!!modelObj.biz) {
		pageProps.biz = modelObj.biz
		pageProps.biz.syncBackCbf = (biz) => {
			dispatch({
				type: `${namespace}/setFormVal`,
				payload: biz
			})
		}
	}
	function goUserAdd(){
		hashHistory.push({
			pathname: '/home/backStageAdmin/userAdd',
			query: {}
		});
	}

	function timeSkip(e){
		//debugger
		// console.log(e)
		hashHistory.push({
			pathname: '/home/backStageAdmin/userEdit',
			query: { accountId:e}
		  });
	   
	}
	//关闭弹出
	function onCancel() {
		dispatch({
			type: `${namespace}/updateStore`,
			payload: {
				showAddVisible: false,
				modalPageData: {
					pageSize: 10,
					pageNo: 1
				},

			}
		})
		fresh()
	}
	//数据更新
	function inputChange(name, value) {
		let obj = { [name]: value }
		detailData = Object.assign(detailData, obj)
		// console.log(detailData);
		dispatch({
			type: `${namespace}/updateStore`,
			payload: { detailData }
		});
	}
	//搜索
	function onSearch() {
		dispatch({
			type: `${namespace}/getFrom4AUser`,
			payload: {
				...detailData, cb: () => { fresh() }
			}
		});
	}
	// 分页
	const pagination = {
		onChange: changePage, //分页事件
	}
	//翻页函数
	function changePage(page, pageSize) {
		dispatch({
			type: `${namespace}/updateStore`,
			payload: {
				modalPageData: {
					pageSize: 10,
					pageNo: page
				} }
		});
		dispatch({
			type: `${namespace}/queryInfo`,
			payload: { pageNo: page, pageSize, name: detailData.name || '李四' }
		});
	}
	return <div className={styles.userList}>
    {/*监控键盘事件，自动刷新数据*/}
		{showAddVisible&&
    <Keypress keyCode={13} cbk={()=>{
      onSearch();
    }} />
		}
		<ListPage pageProps={pageProps} />
	</div>

}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
